<template>
  <Dialog :title="'转账记录'" v-model="dialogVisible" width="1300px" @close="handleClose">
    <!-- 搜索条件 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
      class="mb-4"
    >
      <el-form-item label="转账时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 转账记录表格 -->
    <el-table v-loading="loading" :data="recordList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="转账流水号" align="center" prop="transferNo" width="160px" />
      <el-table-column label="转账时间" align="center" prop="createTime" width="160px">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="转出信息" align="center" width="200px">
        <template #default="scope">
          <div class="font-medium">{{ scope.row.fromMerchantName || '未知商家' }}</div>
          <div class="text-sm">{{ getAccountTypeName(scope.row.fromAccountType) }}</div>
          <div v-if="scope.row.fromAdvertiserId" class="text-sm text-gray-500">
            广告主: {{ scope.row.fromAdvertiserId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="转入信息" align="center" width="200px">
        <template #default="scope">
          <div class="font-medium">{{ scope.row.toMerchantName || '未知商家' }}</div>
          <div class="text-sm">{{ getAccountTypeName(scope.row.toAccountType) }}</div>
          <div v-if="scope.row.toAdvertiserId" class="text-sm text-gray-500">
            广告主: {{ scope.row.toAdvertiserId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="转账金额" align="center" prop="amount" width="120px">
        <template #default="scope">
          <span class="font-semibold text-red-600">{{ scope.row.amount }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="转账状态" align="center" prop="status" width="100px">
        <template #default="scope">
          <dict-tag :type="dictType.JULIANG_TRANSFER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注/失败原因" align="center" min-width="200px">
        <template #default="scope">
          <div v-if="scope.row.status === 2 && scope.row.failReason" class="text-red-600">
            失败原因: {{ scope.row.failReason }}
          </div>
          <div v-else-if="scope.row.remark">
            {{ scope.row.remark }}
          </div>
          <div v-else class="text-gray-400">--</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120px" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            link
            type="primary"
            size="small"
            @click="openAuditDialog(scope.row)"
          >
            审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getRecordList"
      />
    </div>

    <!-- 审核对话框 -->
    <Dialog 
      :title="'转账审核'" 
      v-model="auditDialogVisible" 
      width="700px"
      @close="handleAuditClose"
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="120px"
        v-loading="auditLoading"
      >
        <!-- 转账基本信息 -->
        <div class="audit-section">
          <div class="section-title">
            <Icon icon="ep:info-filled" class="mr-5px" />
            转账基本信息
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="转账流水号">
                <el-input v-model="auditForm.transferNo" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="转账时间">
                <el-input v-model="auditForm.createTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="转账金额">
                <el-input v-model="auditForm.amount" disabled>
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="当前状态">
                <el-tag type="warning" size="large">待审核</el-tag>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 转出方信息 -->
        <div class="audit-section">
          <div class="section-title">
            <Icon icon="ep:arrow-left" class="mr-5px" />
            转出方信息
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="转出商家">
                <el-input v-model="auditForm.fromMerchantName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账户类型">
                <el-input v-model="auditForm.fromAccountTypeName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="auditForm.fromAdvertiserId">
            <el-col :span="12">
              <el-form-item label="广告主ID">
                <el-input v-model="auditForm.fromAdvertiserId" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 转入方信息 -->
        <div class="audit-section">
          <div class="section-title">
            <Icon icon="ep:arrow-right" class="mr-5px" />
            转入方信息
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="转入商家">
                <el-input v-model="auditForm.toMerchantName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账户类型">
                <el-input v-model="auditForm.toAccountTypeName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="auditForm.toAdvertiserId">
            <el-col :span="12">
              <el-form-item label="广告主ID">
                <el-input v-model="auditForm.toAdvertiserId" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 审核信息 -->
        <div class="audit-section">
          <div class="section-title">
            <Icon icon="ep:edit" class="mr-5px" />
            审核信息
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="审核结果" prop="status">
                <el-radio-group v-model="auditForm.status" class="audit-radio-group">
                  <el-radio :label="1" class="audit-radio">
                    <div class="radio-content">
                      <Icon icon="ep:circle-check" class="radio-icon success" />
                      <span>审核通过</span>
                    </div>
                  </el-radio>
                  <el-radio :label="2" class="audit-radio">
                    <div class="radio-content">
                      <Icon icon="ep:circle-close" class="radio-icon danger" />
                      <span>审核失败</span>
                    </div>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="审核备注" prop="remark">
                <el-input
                  v-model="auditForm.remark"
                  type="textarea"
                  :rows="4"
                  :placeholder="auditForm.status === 2 ? '请输入审核失败的原因（至少5个字符）' : '审核通过时可选填写备注'"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false" size="large">取 消</el-button>
          <el-button 
            type="primary" 
            @click="handleAuditSubmit" 
            :loading="auditSubmitLoading"
            size="large"
          >
            <Icon icon="ep:check" class="mr-5px" />
            确认审核
          </el-button>
        </div>
      </template>
    </Dialog>

  </Dialog>
</template>

<script setup lang="ts">
import { AccountBalanceApi } from '@/api/juliang/accountbalance'
import { getDictLabel, DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'

const message = useMessage()

defineOptions({ name: 'TransferRecordDialog' })

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emits = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emits('update:modelValue', value)
})

const loading = ref(false)
const recordList = ref([])
const total = ref(0)
const queryFormRef = ref()
const merchantId = ref<number | undefined>(undefined)

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  fromMerchantId: undefined as number | undefined,
  createTime: [] as string[]
})

// 审核相关
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditSubmitLoading = ref(false)
const auditFormRef = ref()
const auditForm = reactive({
  id: undefined as number | undefined,
  transferNo: '',
  createTime: '',
  amount: '',
  fromMerchantName: '',
  fromAccountTypeName: '',
  fromAdvertiserId: '',
  toMerchantName: '',
  toAccountTypeName: '',
  toAdvertiserId: '',
  status: undefined as number | undefined,
  remark: ''
})

const auditRules = reactive({
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  remark: [
    { 
      required: false, 
      message: '请输入审核备注', 
      trigger: 'blur',
      validator: (rule: any, value: string, callback: any) => {
        if (auditForm.status === 2 && (!value || value.trim().length < 5)) {
          callback(new Error('审核失败时必须填写备注，且至少5个字符'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 获取账户类型中文名称
const getAccountTypeName = (accountType: number) => {
  return getDictLabel(DICT_TYPE.JULIANG_ACCOUNT_TYPE, accountType) || '未知类型'
}

// 暴露DICT_TYPE到模板
const dictType = DICT_TYPE

/** 查询转账记录列表 */
const getRecordList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      fromMerchantId: merchantId.value,
      startTime: queryParams.createTime.length > 0 ? queryParams.createTime[0] : undefined,
      endTime: queryParams.createTime.length > 0 ? queryParams.createTime[1] : undefined
    }

    const data = await AccountBalanceApi.getTransferRecordPage(params)
    recordList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取转账记录失败:', error)
    recordList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getRecordList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 关闭弹窗 */
const handleClose = () => {
  emits('update:modelValue', false)
  resetData()
}

/** 重置数据 */
const resetData = () => {
  recordList.value = []
  total.value = 0
  queryParams.pageNo = 1
  queryParams.createTime = []
  merchantId.value = undefined
}

/** 打开审核对话框 */
const openAuditDialog = (row: any) => {
  auditForm.id = row.id
  auditForm.transferNo = row.transferNo
  auditForm.createTime = formatDate(row.createTime)
  auditForm.amount = row.amount.toString()
  auditForm.fromMerchantName = row.fromMerchantName || '未知商家'
  auditForm.fromAccountTypeName = getAccountTypeName(row.fromAccountType)
  auditForm.fromAdvertiserId = row.fromAdvertiserId || ''
  auditForm.toMerchantName = row.toMerchantName || '未知商家'
  auditForm.toAccountTypeName = getAccountTypeName(row.toAccountType)
  auditForm.toAdvertiserId = row.toAdvertiserId || ''
  auditForm.status = undefined
  auditForm.remark = ''
  
  auditDialogVisible.value = true
}

/** 关闭审核对话框 */
const handleAuditClose = () => {
  auditDialogVisible.value = false
  auditFormRef.value?.resetFields()
  // 重置表单数据
  Object.assign(auditForm, {
    id: undefined,
    transferNo: '',
    createTime: '',
    amount: '',
    fromMerchantName: '',
    fromAccountTypeName: '',
    fromAdvertiserId: '',
    toMerchantName: '',
    toAccountTypeName: '',
    toAdvertiserId: '',
    status: undefined,
    remark: ''
  })
}

/** 提交审核 */
const handleAuditSubmit = async () => {
  try {
    await auditFormRef.value.validate()
    
    auditSubmitLoading.value = true
    
    await AccountBalanceApi.transferBalanceApplyAudit({
      id: auditForm.id!,
      status: auditForm.status!,
      remark: auditForm.remark
    })
    
    message.success('审核提交成功')
    auditDialogVisible.value = false
    getRecordList() // 刷新列表
  } catch (error) {
    console.error('审核提交失败:', error)
    if (error !== 'cancel') {
      message.error('审核提交失败，请重试')
    }
  } finally {
    auditSubmitLoading.value = false
  }
}

/** 打开弹窗 */
const open = (merchant?: { id: number, merchantName: string }) => {
  if (merchant) {
    merchantId.value = merchant.id
    queryParams.fromMerchantId = merchant.id
  }
  emits('update:modelValue', true)
  nextTick(() => {
    getRecordList()
  })
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.text-sm {
  font-size: 12px;
}

.text-gray-500 {
  color: #9ca3af;
}

.font-semibold {
  font-weight: 600;
}

.text-red-600 {
  color: #dc2626;
}

.text-gray-400 {
  color: #9ca3af;
}

.font-medium {
  font-weight: 500;
}

.pagination-wrapper {
  display: flex;
  margin-top: 16px;
  justify-content: center;
  align-items: center;
}

// 修正分页组件在弹窗内的样式
:deep(.el-pagination) {
  .el-pagination__total,
  .el-pagination__jump {
    color: #606266;
  }
  
  .el-pager li {
    margin: 0 2px;
    color: #606266;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    
    &:hover {
      color: #409eff;
    }
    
    &.is-active {
      color: #fff;
      background-color: #409eff;
    }
  }
  
  .btn-prev,
  .btn-next {
    color: #606266;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    
    &:hover {
      color: #409eff;
    }
    
    &:disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }
  
  .el-select .el-input {
    .el-input__wrapper {
      background-color: #fff;
    }
  }
}

// 审核弹窗样式
.audit-section {
  padding: 16px;
  margin-bottom: 24px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  display: flex;
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  align-items: center;
}

.audit-radio-group {
  display: flex;
  gap: 20px;
}

.audit-radio {
  flex: 1;
  
  :deep(.el-radio__label) {
    padding-left: 8px;
  }
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
}

.radio-icon {
  font-size: 18px;
  
  &.success {
    color: #67c23a;
  }
  
  &.danger {
    color: #f56c6c;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}
</style> 